跳到主要内容

4.1-CI、CD

Create by fall on 23 Jun 2023
Recently revised in 25 Feb 2025

Gitlab

gitlab CI/CD

一次代码提交,触发自动化流程

阶段

阶段(stage)

  • build 编译构建
  • test 运行测试
  • deplog 部署到目标环境

作业

执行的命令,最小单位

文件

.gitlab-ci.yml 用于

# 定义阶段执行顺序
stages:
- test
- build
- deploy

# 变量定义
variables:
NODE_VERSION: "18"

# 作业1:代码测试
unit_tests:
stage: test
script:
- npm install
- npm run test:unit
only:
- main
- develop

# 作业2:构建项目
build_project:
stage: build
script:
- npm run build
artifacts:
paths:
- dist/
dependencies: []

# 作业3:部署到生产环境
deploy_production:
stage: deploy
script:
- npm install -g firebase-tools
- firebase deploy --token $FIREBASE_TOKEN
only:
- main
when: manual # 手动触发

定义触发条件

# 基于分支的触发规则
rules:
- if: $CI_COMMIT_BRANCH == "main"
- if: $CI_COMMIT_BRANCH == "develop"

# 基于合并请求
only:
- merge_requests
# 缓存(加速重复文件)
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/

示例

React 项目

image: node:18-alpine

stages:
- install
- lint
- test
- build
- deploy

cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/

before_script:
- npm ci --cache .npm --prefer-offline

lint_code:
stage: lint
script:
- npm run lint

unit_tests:
stage: test
script:
- npm run test:unit

build_project:
stage: build
script:
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 week

deploy_to_pages:
stage: deploy
script:
- cp -r dist/ public/
artifacts:
paths:
- public
only:
- main
# 错误处理
on_failure:
script:
- echo "Pipeline failed!"
- send-slack-notification.sh

参考文章

名称链接
官方文档https://learn.microsoft.com/zh-cn/windows/wsl/install